package com.keyinong.caizhengting.pay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import org.apache.http.Header;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.Tools.HttpTools;
import com.keyinong.caizhengting.view.DingcanActivity;
import com.loopj.android.http.JsonHttpResponseHandler;

/**个人支付宝支�??*/

public class PayDemoActivity extends FragmentActivity {

	// 商户PID
	public static final String PARTNER = "2088911738962659";
	// 商户收款账号
	public static final String SELLER = "admin@jishi88.com";
	// 商户私钥，pkcs8格式
	public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAN0YrXSRsFGVpK6YW4q8YWEeN8vCIwg/EYdLnn1gGAoZlNsoWItS/4w/FI7dD08xqazn9TRwyEW5NEqYQ9LHRLeJ+soNDKMJhTGKqwZEgTosZHuOIARGEW6G/9qsKYfHyk1jBw/fc1RF5P06l+1fbvnLvUkpD+scUDzzyYdXXJxHAgMBAAECgYEAuDdQhtjArSle3m5pj43oITA5Uxd9cuiBpVX3RwVi4j9wTK4wIF3WOLdyXJqJn/WEJ2HZZ4k1BQsMK770e9G2SR406ciC8oDWTEyBQL2RO6m0Poc/wohptzLZGzhK39/wpY/L/kb0lEcchdYFkCuNUAwvWIYpd4rz8DzB2GgMW2kCQQDyJMskPaKZ/dhGGM7HrIjWtTwM5sPmmQZD6HXn1q7+54f9bUfabp+dwrxxD3hoHWruKlK+Ahhs+4IgfYAzCEq1AkEA6b+O2FJH8i5KbQcij23Z11efzZfjiAlLMBRI9sJNvOB557gyuAxFePY/7nI4RGjKQOWR/oWYHiOuR/ji5ddciwJAHuF+XsLVh9oNyPLE/EYOtYMrg2Gyvifp2qM81jJU4wFYIIPdVAgjpxT8v1Z/vpdx2angH4dY4h05PTeEL/3wuQJAc8nAKMgZe44SsA9ov0PbNSDiuCUVQL3Z0Oc7fYCioX1Q5cgI18K8Zz8UTDmoRbri9WLC/yGOSN/D5UMUomYcIQJBAK36GXIZMjiiJs95CsNgkw/oXP1srWneDG3FUvJz10UIGWI/uAOUz2hzKMK76kfgifgjWdxNQZobLPtI7nLmTCw=";
	// 支付宝公�??
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
	private static final int SDK_PAY_FLAG = 1;
	/**价格*/
	private TextView tv_price;
	private String price;
	/**返回*/
	private ImageButton ib_back;
	/**网络请求*/
	HttpTools httptools=null;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				/**
				 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
				 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
				 * docType=1) 建议商户依赖异步通知
				 */
				String resultInfo = payResult.getResult();// 同步返回�??要验证的信息

				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为�??9000”则代表支付成功，具体状态码代表含义可参考接口文�??
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(PayDemoActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					String id = getIntent().getStringExtra("orderid");
					Log.i("shi", "id---"+id);
					if(httptools==null){
						httptools = new HttpTools(getApplicationContext());
					}
					httptools.aliPay(id, new JsonHttpResponseHandler(){
						public void onSuccess(int statusCode, Header[] headers,
								JSONObject response) {
							// TODO Auto-generated method stub
							super.onSuccess(statusCode, headers, response);
							Log.i("zq",response.toString());

						}
					});
					Intent intent = new Intent();
					intent.setClass(getApplicationContext(), DingcanActivity.class);
					startActivity(intent);
					finish();
				} else {
					// 判断resultStatus 为非"9000"则代表可能支付失�??
					// "8000"代表支付结果因为支付渠道原因或�?�系统原因还在等待支付结果确认，�??终交易是否成功以服务端异步�?�知为准（小概率状�?�）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PayDemoActivity.this, "支付结果确认�??",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(PayDemoActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.pay_external);
		ib_back=(ImageButton)findViewById(R.id.ib_fanhui6);
		ib_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		tv_price=(TextView)findViewById(R.id.product_price);
		price = getIntent().getStringExtra("price");		
		tv_price.setText("�??"+price+"�??");
	}

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(View v) {
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE)
				|| TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(this)
			.setTitle("警告")
			.setMessage("�??要配置PARTNER | RSA_PRIVATE| SELLER")
			.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
				public void onClick(
						DialogInterface dialoginterface, int i) {
					//
					finish();
				}
			}).show();
			return;
		}

		String orderInfo = getOrderInfo("番茄订餐", "企业订餐",price );

		/**
		 * 特别注意，这里的签名逻辑�??要放在服务端，切勿将私钥泄露在代码中�??
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		/**
		 * 完整的符合支付宝参数规范的订单信�??
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构�?�PayTask 对象
				PayTask alipay = new PayTask(PayDemoActivity.this);
				// 调用支付接口，获取支付结�??
				String result = alipay.pay(payInfo, true);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本�??
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账�??
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单�??
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步�?�知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm"
				+ "\"";

		// 服务接口名称�?? 固定�??
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型�?? 固定�??
		orderInfo += "&payment_type=\"1\"";

		// 参数编码�?? 固定�??
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭�??
		// 取�?�范围：1m�??15d�??
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）�??
		// 该参数数值不接受小数点，�??1.5h，可转换�??90m�??
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支�??
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可�??
		orderInfo += "&return_url=\"m.alipay.com\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该�?�在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签�??
	 * 
	 * @param content
	 *            待签名订单信�??
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
